package com.wude.guild.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mc.developmentkit.utils.ToastUtil;
import com.umeng.analytics.MobclickAgent;
import com.wude.bean.AboutUs;
import com.wude.bean.SettingInfo;
import com.wude.guild.DownloadActivity;
import com.wude.guild.R;
import com.wude.guild.dialog.MillionDialog;
import com.wude.guild.manager.CheckedChangeLis;
import com.wude.guild.servercore.mints.TitleBaseFragment;
import com.wude.guild.views.SwitchButton;
import com.wude.http.HttpCom;
import com.wude.http.HttpUtils;
import com.wude.tools.CleanMessageUtil;
import com.wude.tools.Utils;

import org.xutils.common.Callback;
import org.xutils.common.task.PriorityExecutor;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.concurrent.Executor;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2017/11/23 0023.
 */

public class SettingFragment extends TitleBaseFragment {
    private Unbinder unbinder;

    @BindView(R.id.wangluo)
    SwitchButton wangluo;
    @BindView(R.id.delete)
    SwitchButton delete;
    @BindView(R.id.anzhuang)
    SwitchButton anzhuang;
    @BindView(R.id.qingli)
    RelativeLayout qingli;
    @BindView(R.id.banben)
    TextView banben;
    @BindView(R.id.version)
    RelativeLayout version;
    @BindView(R.id.tuichu)
    RelativeLayout tuichu;
    @BindView(R.id.news)
    ImageView news;
    @BindView(R.id.zhazha)
    TextView zhazha;
    @BindView(R.id.xiazai)
    RelativeLayout xiazai;
    private int i;
    private AboutUs about;
    private final static Executor exec = new PriorityExecutor(1, true);//成员常量
    private boolean zhong = true;

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_setting, container, false);
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("SettingFragment");
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("SettingFragment");
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        unbinder = ButterKnife.bind(this, view);

        setHeaderTitle("设置");
        initData();
    }

    private void initData() {
        HttpCom.POST(handler, HttpCom.getVisonURL(), null, false);
        CheckedChangeLis checkedChangeLis = new CheckedChangeLis(getActivity());
        wangluo.setOnCheckedChangeListener(checkedChangeLis);
        delete.setOnCheckedChangeListener(checkedChangeLis);
        anzhuang.setOnCheckedChangeListener(checkedChangeLis);
        SettingInfo settingBean = Utils.getSettingBean();
        if (settingBean != null) {
            Display(settingBean);
        } else {
            ToastUtil.showToast("settingBean为空");
        }
        qingli();
    }

    public void qingli() {
        try {
            String totalCacheSize = CleanMessageUtil.getTotalCacheSize(x.app());
            zhazha.setText(totalCacheSize);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("获取缓存异常", e.toString());
        }
    }

    /**
     * 设置三个按钮的显示
     *
     * @param settingBean
     */
    private void Display(SettingInfo settingBean) {
        if (settingBean.tan == 1) {
            anzhuang.setChecked(true);
        } else {
            anzhuang.setChecked(false);
        }
        if (settingBean.delete == 1) {
            delete.setChecked(true);
        } else {
            delete.setChecked(false);
        }
        if (settingBean.wlti == 1) {
            wangluo.setChecked(true);
        } else {
            wangluo.setChecked(false);
        }
    }

    @OnClick({R.id.qingli, R.id.version, R.id.tuichu, R.id.xiazai})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.xiazai:                   //下载管理
                startActivity(new Intent(getContext(), DownloadActivity.class));
                break;
            case R.id.qingli:               //清理
                Clear();
                break;
            case R.id.version:              //版本更新
                if (i == 1 && about != null && zhong == true) {
                    if (banben.getText().toString().equals("安装")) {
                        File apkFile = Utils.getApkFile(String.valueOf(00001));
                        Utils.installApp(Utils.getContext(), apkFile);
                    } else {
                        if (about.versionUrl != null && !about.versionUrl.equals("")) {
                            StartDown(about.versionUrl);
                        } else {
                            ToastUtil.showToast("下载链接为空");
                        }
                    }
                }
                break;
            case R.id.tuichu:                   //退出登录
                SignoutLoading();
                break;
        }
    }

    /**
     * 退出登录
     */
    private void SignoutLoading() {
        final MillionDialog millionDialog = new MillionDialog(getContext(), R.style.MillionDialogStyle);
        millionDialog.setTitle("退出登录");
        millionDialog.setContext("您确认退出当前账号吗？");
        millionDialog.setOkListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                millionDialog.dismiss();
                ToastUtil.showToast("退出");
            }
        });
        millionDialog.show();
    }


    /**
     * 清理缓存
     */
    private void Clear() {
        if (zhazha.getText().toString().equals("0KB")) {
            ToastUtil.showToast("暂无缓存垃圾");
            return;
        }
        final MillionDialog millionDialog = new MillionDialog(getContext(), R.style.MillionDialogStyle);
        millionDialog.setTitle("确认清除缓存");
        millionDialog.setContext("您确认清除所有缓存吗？");
        millionDialog.setOkListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                millionDialog.dismiss();
                CleanMessageUtil.clearAllCache(x.app());
                qingli();
            }
        });
        millionDialog.show();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    /**
     * 刚进来请求
     */
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    about = HttpUtils.DNSAboutUs(msg.obj.toString());
                    i = Utils.verison_update(about.version_hao, about.versionUrl);
                    switch (i) {
                        case 1:
                            File apkFile = Utils.getApkFile(String.valueOf(00001));
                            if (apkFile.exists()) {
                                banben.setText("安装");
                            } else {
                                news.setVisibility(View.VISIBLE);
                                banben.setVisibility(View.GONE);
                            }
                            break;
                        case 2:
                            banben.setText("版本：" + about.version_name + "(最新)");
                            break;
                        case 3:
                            banben.setText("后台版本号格式填写有误");
                            break;
                        case 4:
                            banben.setText("服务端版本小于本地版本");
                            break;
                    }
                    break;
                case 2:
                    ToastUtil.showToast("网络异常");
                    break;
            }
        }
    };

    //下载
    protected void StartDown(String url) {
        RequestParams entity = new RequestParams(url);
        entity.setAutoResume(true);//是否断点下载
        entity.setAutoRename(false);//下载完成后是否自动重命名
        entity.setCancelFast(true);//快速取消
        entity.setExecutor(exec);//线程池
        entity.setSaveFilePath(Utils.getApkFile(String.valueOf(00001)).getAbsolutePath());//文件保存路径
        Callback.Cancelable cancelable = x.http().get(entity, new Callback.ProgressCallback<File>() {

            @Override
            public void onCancelled(CancelledException arg0) {
            }

            @Override
            public void onError(Throwable arg0, boolean arg1) {
                ToastUtil.showToast("更新失败");
                news.setVisibility(View.VISIBLE);
                banben.setVisibility(View.GONE);
                Log.e("更新失败原因", arg0.toString());
                zhong = true;
            }

            @Override
            public void onFinished() {

            }

            @Override
            public void onSuccess(File arg0) {
                File apkFile = Utils.getApkFile(String.valueOf(00001));
                Utils.installApp(Utils.getContext(), apkFile);
                banben.setText("安装");
                zhong = true;
            }

            @Override
            public void onLoading(long arg0, long arg1, boolean arg2) {
                int progress = (int) (arg1 * 100f / arg0 + 0.5f);
                banben.setText(progress + "%");
            }

            @Override
            public void onStarted() {
                banben.setText("0%");
            }

            @Override
            public void onWaiting() {
                zhong = false;
                news.setVisibility(View.GONE);
                banben.setVisibility(View.VISIBLE);
                banben.setText("等待");
            }
        });
    }
}
